import React, { useEffect, useState, useCallback } from "react";
import {
  Card,
  Table,
  Button,
  Form,
  Input,
  Space,
  Popconfirm,
  Modal,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  SearchOutlined,
  QuestionCircleOutlined,
  CheckOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import aclApi from "@/api/acl";
import { type ItemsModel } from "@/api/acl/model/roleAuth";

export default function RoleAuth() {
  const [form] = Form.useForm();
  const [formModal] = Form.useForm();
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [total, setTotal] = useState(0);
  const [roleIn, setroLeIn] = useState<ItemsModel[]>();
  const [visible, setVisible] = useState(false);
  const [rolName, setrolName] = useState("");
  const [ids, setIds] = useState<any>([]);

  const [selectionType, setSelectionType] = useState<"checkbox" | "radio">(
    "checkbox"
  );

  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
  }

  const columns: ColumnsType<any> = [
    {
      title: "序号",
      width: 80,
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
      width: "50%",
      render: (value, row, index) => {
        return (
          <div>
            {row.inputBoon ? (
              <div>
                <input
                  type="text"
                  value={value}
                  onChange={(e) => {

                    let newLe = roleIn?.map((item) => {
                      if (item.id == row.id) {
                        item.roleName = e.target.value;
                      }
                      return item;
                    });
                    setroLeIn(newLe);
                  }}
                />
                <button
                  onClick={() => {
                    console.log(row);

                    let newIn = roleIn?.map((item) => {
                      item.inputBoon = false;
                      if (item.id == row.id) {
                        item.roleName = rolName
                      }
                      return item;
                    });
                    setroLeIn(newIn);
                  }}
                >
                  取消
                </button>
              </div>
            ) : (
              <div>{value}</div>
            )}
          </div>
        );
      },
    },
    {
      title: "操作",
      render: (value, row, index) => {
        return (
          <Space>
            <Button
              icon={<QuestionCircleOutlined />}
              type="primary"
              style={{ background: "#909399" }}
            ></Button>
            <Button
              icon={<CheckOutlined />}
              type="primary"
              onClick={async () => {
                try {
                  await aclApi.updateRoleApi(row);
                  inFalse(row);
                  message.success("更新成功");
                } catch (error) {
                  console.log(error);
                }
              }}
            ></Button>
            <Button
              icon={<FormOutlined />}
              type="primary"
              onClick={() => {
                inTrOrFa(row);
                setrolName(row.roleName)
                
              }}
            ></Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={async () => {
                try {
                  await aclApi.removeRoleApi(row.id);
                  roleInfo(page, limit);
                  message.success("删除成功");
                } catch (error) {
                  console.log(error);
                }
              }}
            ></Button>
          </Space>
        );
      },
    },
  ];

  // 控制input显示
  let inTrOrFa = (value: ItemsModel) => {
    let newIn = roleIn?.map((item) => {
      item.inputBoon = false;
      if (item.id == value.id) {
        item.inputBoon = !item.inputBoon;
      }
      return item;
    });

    setroLeIn(newIn);
  };
  // 点击取消 input 消失
  let inFalse = (row: ItemsModel) => {
    let newIn = roleIn?.map((item) => {
      item.inputBoon = false;
      return item;
    });
    setroLeIn(newIn);
  };
  // 数据初始化
  let roleInfo = useCallback(
    async (page: number, limit: number, roleName?: string) => {
      try {
        let result = await aclApi.getRole(page, limit, roleName);
        setTotal(result.total);
        setroLeIn(result.items);
      } catch (error) {
        console.log(error);
      }
    },
    [page, limit]
  );
  useEffect(() => {
    roleInfo(page, limit);
  }, [roleInfo]);

  // 多选框
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      let newIds = [];
      newIds.push(selectedRowKeys);
      console.log(newIds);

      setIds(newIds);
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === "Disabled User", // Column configuration not to be checked
      name: record.name,
    }),
  };
  // 搜索
  const onFinish = (values: any) => {
    roleInfo(1, limit, values.roleName);
  };
  // 收集表单数据
  const collectRole = (changedValues: any, allValues: any) => {
    setrolName(changedValues.roleName);
  };
  // 添加
  const addRole = async () => {
    try {
      await aclApi.getAddRole({ roleName: rolName });
      setVisible(false);
      roleInfo(page, limit);
    } catch (error) {
      console.log(error);
    }
  };
  // 取消
  const cancelRole = () => {
    setVisible(false);
    formModal.resetFields();
  };
  return (
    <Card>
      <Form
        form={form}
        name="horizontal_login"
        layout="inline"
        onFinish={onFinish}
        className="mb"
      >
        <Form.Item
          name="roleName"
          rules={[{ required: true, message: "查询条件不可为空" }]}
        >
          <Input placeholder="角色名称" />
        </Form.Item>

        <Form.Item shouldUpdate>
          <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
            查询
          </Button>
          <Button
            style={{ margin: "0 8px" }}
            onClick={() => {
              form.resetFields();
              roleInfo(1, limit);
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>

      <div className="mt-20">
        <Button
          type="primary"
          htmlType="submit"
          onClick={() => {
            setVisible(true);
          }}
        >
          添加
        </Button>
        <Button
          style={{ margin: "0 8px" }}
          type="primary"
          danger
          disabled={ids.length == 0}
          onClick={() => {
            try {
              aclApi.removeRolesApi(ids);
              roleInfo(page, limit);
            } catch (error) {
              console.log(error);
            }
          }}
        >
          批量删除
        </Button>
      </div>

      <Table
        className="mt-10"
        columns={columns}
        dataSource={roleIn}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        bordered
        pagination={{
          total,
          current: page,
          pageSize: limit,
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [10, 20, 30, 40],
          onChange: (page, limit) => {
            setPage(page);
            setLimit(limit);
          },
        }}
        rowKey="id"
      />
      <Modal
        title="添加角色"
        visible={visible}
        footer={null}
        onCancel={cancelRole}
      >
        <Form
          form={formModal}
          layout="vertical"
          name="addrole"
          onValuesChange={collectRole}
        >
          <Form.Item label="请输入新名称" name="roleName">
            <Input placeholder="请输入新名称" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" style={{ marginRight: 8 }} onClick={addRole}>
              保存
            </Button>
            <Button onClick={cancelRole}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
}
